package com.orhon.smartcampus.modules.schoolaffairs.fetcher;

import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSchool;
import com.orhon.smartcampus.modules.base.mm.SchoolMapper;
import com.orhon.smartcampus.modules.schoolaffairs.dao.SchoolNewsDao;
import com.orhon.smartcampus.modules.schoolaffairs.dao.SchoolNoticeDao;
import com.orhon.smartcampus.modules.schoolaffairs.entity.SchoolNews;
import com.orhon.smartcampus.modules.schoolaffairs.entity.SchoolNotice;
import com.orhon.smartcampus.modules.schoolaffairs.gqlModel.GQLSchoolNews;
import com.orhon.smartcampus.modules.schoolaffairs.gqlModel.GQLSchoolNotice;
import com.orhon.smartcampus.modules.schoolaffairs.nm.SchoolNewsMapper;
import com.orhon.smartcampus.modules.schoolaffairs.nm.SchoolNoticeMapper;
import com.orhon.smartcampus.modules.student.entity.Eclass;
import com.orhon.smartcampus.modules.student.gqlModel.GQLEclass;
import com.orhon.smartcampus.modules.student.mm.EclassMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.utils.R;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SchoolNoticeFetcher implements DataFetcher {

    @Autowired
    TokenService tokenService;

    @Autowired
    SchoolNoticeDao schoolNoticeDao;

    @Override
    public Object get(DataFetchingEnvironment env) throws Exception {
        String token = tokenService.getSystemToken();
        if(token==null) {
            return  R.NoLogin();
        }
        Long schoolId = JwtUtils.getSchoolId(token);
        int id = Integer.parseInt(env.getArgument("id").toString());
        String hql = "from SchoolNotice where deleted_at = null and id = "+id+" and school_id = " + schoolId;
        SchoolNotice schoolNotice = schoolNoticeDao.findId(hql, null);
        if(schoolNotice!=null){
            GQLSchool gqlSchool = null;
            if (env.getSelectionSet().contains("school")){
                schoolNotice.getSchoolsBySchool().toString();
                Schools schoolsBySchool = schoolNotice.getSchoolsBySchool();
                gqlSchool = SchoolMapper.MAPPER.toSchool(schoolsBySchool);
            }
            GQLEclass gqlEclass = null;
            if(env.getSelectionSet().contains("eclass")){
                schoolNotice.getEclass().toString();
                Eclass eclass = schoolNotice.getEclass();
                gqlEclass= EclassMapper.MAPPER.toEclass(eclass);

            }
            GQLSchoolNotice gqlSchoolNews = SchoolNoticeMapper.MAPPER.toSchoolNotice(schoolNotice);
            gqlSchoolNews.setSchool(gqlSchool);
            gqlSchoolNews.setEclass(gqlEclass);
            return gqlSchoolNews;
        }
        return null;
    }
}
